# -*- encoding:utf-8 -*-
import requests
import random
from StringIO import StringIO
import json
s=requests.session()
captcha_server_conf = {
    #"host": "127.0.0.1",
    'host': '101.201.102.37',
    "port": 9301
}
captcha_server_url = "http://101.201.102.37:9301/get_captcha"


def get_captcha_url( session):
    return "http://218.57.139.24/securitycode?%s" % (str(random.random()))
for break_num in xrange(5):
    try:
        captcha_url = get_captcha_url(s)
        r = s.get(captcha_url)
        cap_content = r.content
        post_image = {'captcha': StringIO(cap_content)}
        print 'aa'
        with open('a','wb') as f:
            f.write(cap_content)
        post_data = {
            'province': 'shandong'
        }
        result = requests.post(captcha_server_url, data=post_data, files=post_image)
        result_json = json.loads(result.content)
        status = int(result_json['status'])
        # 识别失败
        if status is not 0:
            continue
        captcha_result = str(result_json['result'])
        print captcha_result
        break
    except Exception as  e:
        print e
        pass